package cn.geminis.crypto.csp.parameter;

import org.bouncycastle.asn1.*;
import org.bouncycastle.crypto.CipherParameters;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author Allen
 */
public class InitAgreementCipherParameters implements CipherParameters {

    private boolean initiator;
    private byte[] id;

    public InitAgreementCipherParameters(boolean initiator, byte[] id) {
        this.initiator = initiator;
        this.id = id;
    }

    public InitAgreementCipherParameters(byte[] data) {
        try {
            ASN1Sequence sequence = (ASN1Sequence) DERSequence.fromByteArray(data);
            this.initiator = ASN1Boolean.getInstance(sequence.getObjectAt(0)).isTrue();
            this.id = DEROctetString.getInstance(sequence.getObjectAt(1)).getOctets();
        } catch (IOException e) {
            throw new RuntimeException("解析密钥协商初始化参数错误", e);
        }
    }


    public boolean isInitiator() {
        return initiator;
    }

    public byte[] getId() {
        return id;
    }

    public byte[] encode() {
        try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
            DERSequenceGenerator generator = new DERSequenceGenerator(stream);
            generator.addObject(ASN1Boolean.getInstance(this.initiator));
            generator.addObject(new DEROctetString(this.id));
            generator.close();
            return stream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("密钥协商初始化参数编码错误", e);
        }
    }

}
